import logging
import random

import captcha
# Create your views here.
from django import http
from django.views import View
from django_redis import get_redis_connection

from random import randint

from captcha.image import ImageCaptcha

from meiduo_mall.utils.response_code  import RETCODE
from . import constants


from celery_tasks.sms.tasks import send_sms_code
# 创建日志输出带


logger=logging.getLogger('django')


class ImageCodeView(View):
    # 图形验证码
    def get(self,request,uuid):
        # text,image=captcha.generate_captcha()
        image = ImageCaptcha()
        text = ''
        for i in range(4):
            s = str(randint(0, 9))
            text = text + s
        path='meiduo_mall/apps/verifications/verify_code/out.png'
        image.write(text,path )
        with open(path,mode='rb')as f:
            img=f.read()
        text=text.encode()
        redis_conn=get_redis_connection('verify_code')
        redis_conn.setex('img_%s'%uuid,constants.IMAGE_CODE_REDIS_EXPIRES,text)
        # print(redis_conn.get('img_%s' % uuid))

        return  http.HttpResponse(img,content_type='image/png')

class SMSCodeView(View):
    # 短信验证码
    def get(self,request,mobile):
        '''
        :param request:
        :param mobile: 手机号
        :return: json
        '''
        # 1.接受参数
        image_code_client=request.GET.get('image_code')
        uuid = request.GET.get('uuid')
        # 2.校验参数
        if not all([image_code_client,uuid]):
            return http.HttpResponseForbidden('缺少比传参数')
        # 3.主业务
        # 创建redis链接对象
        redis_conn = get_redis_connection('verify_code')

        # 判断是否频繁发送短信验证码
        send_flag=redis_conn.get('send_flag_%s'%mobile)
        if send_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信验证码过于频繁'})

        # 3.1 提取图形验证码
        image_code_server=redis_conn.get('img_%s'%uuid)
        if image_code_server is None:
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'验证码已失效'})
        # 3.2 删除redis的验证码
        redis_conn.delete('img_%s'%uuid)
        # 3.3对比图形验证码
        image_code_server=image_code_server.decode()
        if image_code_server.lower() != image_code_client.lower():
            return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图形验证码有误'})
        # 3.4 生成短信验证码
        sms_code='%06d'%random.randint(0,999999)
        # 记录短信验证码
        logger.info('短信验证码：'+sms_code)
        # # 3.5 保存短信验证码
        # redis_conn.setex('sms_%s'%mobile,constants.IMAGE_CODE_REDIS_EXPIRES,sms_code)
        # # 保存发送短信验证码的标记
        # redis_conn.setex('send_flag_%s'%mobile,constants.SEND_SMS_CODE_INTERVAL,1)
        # 创建pipeline管道
        pl=redis_conn.pipeline()
        pl.setex('sms_%s'%mobile,constants.IMAGE_CODE_REDIS_EXPIRES,sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()

        # 3.6 发送短信验证码--转交给celery移步执行
        # CCP().send_message(constants.SEND_SMS_TEMPLATE_ID,mobile,(sms_code,constants.SMS_CODE_REDIS_EXPIRES // 60))
        send_sms_code.delay(mobile,sms_code) #一定要用delay
        # 4.响应成功
        return http.JsonResponse({'code':RETCODE.OK,'errmsg':'发送短信成功'})


